import { defineStore } from 'pinia'
import { ref } from 'vue'
import { setLocale, type Locale } from '../i18n'

export const useAppStore = defineStore('app', () => {
  // State
  const theme = ref<'light' | 'dark'>('light')
  const sidebarCollapsed = ref(false)
  const appVersion = ref('1.0.0')
  const currentLocale = ref<Locale>(localStorage.getItem('locale') as Locale || 'zh-CN')
  
  // Actions
  function toggleTheme() {
    theme.value = theme.value === 'light' ? 'dark' : 'light'
    applyTheme()
  }
  
  function toggleSidebar() {
    sidebarCollapsed.value = !sidebarCollapsed.value
  }
  
  function applyTheme() {
    document.documentElement.setAttribute('data-theme', theme.value)
    if (theme.value === 'dark') {
      document.documentElement.classList.add('dark')
    } else {
      document.documentElement.classList.remove('dark')
    }
    // 保存到本地存储
    localStorage.setItem('theme', theme.value)
  }
  
  // 切换语言
  function changeLocale(locale: Locale) {
    currentLocale.value = locale
    setLocale(locale)
  }
  
  // 初始化
  function init() {
    // 初始化主题
    const savedTheme = localStorage.getItem('theme') as 'light' | 'dark' | null
    if (savedTheme) {
      theme.value = savedTheme
      applyTheme()
    }
    
    // 初始化语言
    const savedLocale = localStorage.getItem('locale') as Locale | null
    if (savedLocale) {
      currentLocale.value = savedLocale
      setLocale(savedLocale)
    }
  }
  
  return {
    theme,
    sidebarCollapsed,
    appVersion,
    currentLocale,
    toggleTheme,
    toggleSidebar,
    changeLocale,
    init,
    initTheme: init // 保持向后兼容
  }
}) 